package org.grayrabbit.cms.plugin.loaders;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.List;

import org.grayrabbit.cms.plugin.ModuleDescriptorFactory;
import org.grayrabbit.cms.plugin.Plugin;
import org.grayrabbit.cms.plugin.PluginParseException;
import org.grayrabbit.cms.utils.ClassLoaderUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * @author sys53
 * @version 1.0
 * @created 06-一月-2012 16:15:47
 */
public class ClassPathPluginLoader implements PluginLoader {
	private static Logger log = LoggerFactory.getLogger(ClassPathPluginLoader.class);
	List<Plugin> plugins;
	private String fileNameToLoad;

	public ClassPathPluginLoader(){
		this("cms-plugin.xml");
	}
	public ClassPathPluginLoader(String fileNameToLoad) {
		this.fileNameToLoad = fileNameToLoad;
	}
	public Collection<Plugin> loadAllPlugins(ModuleDescriptorFactory moduleDescriptorFactory) {
		if (this.plugins == null)
	    {
	      loadClassPathPlugins(moduleDescriptorFactory);
	    }
	    return this.plugins;
	}

	private void loadClassPathPlugins(ModuleDescriptorFactory moduleDescriptorFactory) {
		URL url = null;
		this.plugins = new ArrayList<Plugin>();
		Enumeration<URL> pluginDescriptorFiles;
		try {
			pluginDescriptorFiles = ClassLoaderUtils.getResources(this.fileNameToLoad, getClass());
		} catch (IOException e) {
			log.error("Could not load classpath plugins: " + e, e);
			return;
		}
		while (pluginDescriptorFiles.hasMoreElements()) {
			url = (URL) pluginDescriptorFiles.nextElement();
			try {
				SinglePluginLoader loader = new SinglePluginLoader(url.openConnection().getInputStream());
				this.plugins.addAll(loader.loadAllPlugins(moduleDescriptorFactory));
			} catch (IOException e) {
				log.error("IOException parsing inputstream for : " + url, e);
			} catch (PluginParseException e) {
				log.error("Unable to load plugin at url: " + url + ", "+ e.getMessage(), e);
			}
		}
	}
	public void removePlugin(Plugin plugin) {
		
	}

	public boolean supportsAddition() {
		return true;
	}

	public boolean supportsRemoval() {
		return true;
	}



}